package rwt.server.handlers.web;

import rwt.server.*;
import rwt.server.RailroadMessages.SwReqMsg;
import rwt.server.WebMessages.SetSwitch;
import rwt.server.core.*;
import rwt.server.railroad.Switches;

public class SetSwitchHandler  extends MessageHandler<SetSwitch>
{

	@Override
	public void handle(SetSwitch message, IConnection source) throws Exception 
	{
		//check if server is running
		if (!RailServer.getController().isConnected() || !RailServer.getRailroadServer().isConnected())
			return;
		
		if (!(source instanceof IClient))
			throw new IllegalArgumentException("SetSwitch did not come from a client.");
		
		IClient client = (IClient) source;
		int changedSwitchStatus = RailServer.getSwitchManager().changeSwitchState(message.switchId);
		SwReqMsg msg = new SwReqMsg(message.switchId, changedSwitchStatus);
		if (Switches.getInstance().isValid(client))
		{
			if (Switches.getInstance().isEmergency())
				RailServer.getRailroadServer().write(msg);
			else
				RailServer.getController().write(msg);
		}
	}

}
